import HeaderDropdown from './HeaderDropdown';
import {useEmotionCss} from '@ant-design/use-emotion-css';
import {setAlpha} from '@ant-design/pro-components';
import {LogoutOutlined, UserOutlined, ExclamationCircleFilled} from '@ant-design/icons';
import {useModel, history} from 'umi';
import {useCallback} from 'react';
import {stringify} from 'querystring';
import {flushSync} from 'react-dom';
import {Avatar, Modal} from 'antd';

/* 显示名称 */
const Name = () => {
  const {initialState} = useModel('@@initialState');
  const {loginInfo} = initialState || {};

  const nameClassName = useEmotionCss(({token}) => {
    return {
      width: '70px',
      height: '48px',
      overflow: 'hidden',
      lineHeight: '48px',
      whiteSpace: 'nowrap',
      textOverflow: 'ellipsis',
      [`@media only screen and (max-width: ${token.screenMD}px)`]: {
        display: 'none',
      },
    };
  });

  return <span className={`${nameClassName} anticon`}>{loginInfo?.nickname}</span>;
};

/* 显示头像 */
const AvatarLogo = () => {
  const {initialState} = useModel('@@initialState');
  const {loginInfo} = initialState || {};
  if (loginInfo && !loginInfo.avatar) {
    loginInfo.avatar = '/image/avatar.png';
  }

  const avatarClassName = useEmotionCss(({token}) => {
    return {
      marginRight: '8px',
      color: token.colorPrimary,
      verticalAlign: 'top',
      background: setAlpha(token.colorBgContainer, 0.85),
      [`@media only screen and (max-width: ${token.screenMD}px)`]: {
        margin: 0,
      },
    };
  });

  return <Avatar size='small' className={avatarClassName} src={loginInfo?.avatar} alt='avatar'/>;
};

const AvatarDropdown = () => {

  const {setInitialState} = useModel('@@initialState');

  /* 退出登录，并且将当前的 url 保存 */
  const loginOut = async () => {
    const {search, pathname} = window.location;
    let code = window.localStorage.getItem('code') || '';
    window.localStorage.clear();
    history.replace({
      pathname: '/login',
      search: stringify({code, redirect: pathname + search}),
    });
  };

  /* 监听下拉菜单 */
  const onMenuClick = useCallback(
    (event) => {
      const {key} = event;
      /* 退出登录 */
      if (key === 'logout') {
        Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleFilled/>,
          content: '确定退出系统登录吗？',
          onOk() {
            flushSync(() => {
              setInitialState((s) => ({...s, loginInfo: undefined}));
            });
            loginOut().then();
          },
        });
      }
      /* 个人中心 */
      if (key === 'ucenter') {
        history.push('/ucenter');
      }
    },
    [setInitialState],
  );

  const menuItems = [
    {key: 'ucenter', icon: <UserOutlined/>, label: '个人中心'},
    {type: 'divider'},
    {key: 'logout', icon: <LogoutOutlined/>, label: '退出登录'},
  ];

  const actionClassName = useEmotionCss(({token}) => {
    return {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      <span className={actionClassName}>
        <AvatarLogo/>
        <Name/>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
